//
//  DomainSwitchInterceptor.swift
//  Mediaplayer
//
//  Created by bin hu on 2025/7/14.
//

import UIKit
import Alamofire

/// 自定义拦截器（支持状态码过滤）
final class DomainSwitchInterceptor: RequestInterceptor {
    // 可配置属性
    private let retryDelay: TimeInterval = 1.0
    // 定义需要过滤的状态码（这些状态码不会触发重试）
    private let filteredStatusCodes: Set<Int> = [200, 401, 601, 602]
    // 当前重试次数
    private var currentRetryCount = 0
    // 线程安全计数器
    private let lock = NSLock()
    
    func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
        // 清理旧域名连接
        session.session.getAllTasks { tasks in
            tasks.forEach { $0.cancel() }
        }
        
        var request = urlRequest
        
        // 替换请求的域名
        if let originalUrl = request.url,
           let originalHost = originalUrl.host,
           let newUrl = URL(string: originalUrl.absoluteString.replacingOccurrences(
            of: originalHost,
            with: DomainManager.shared.currentDomain
           )) {
            request.url = newUrl
        }
        
        // 添加自定义头
        request.headers.add(.authorization(bearerToken: "your_auth_token"))
        request.headers.add(name: "X-Domain-Used", value: DomainManager.shared.currentDomain)
        
        DomainManager.shared.reportSuccess(for: DomainManager.shared.currentDomain)
        completion(.success(request))
    }
    
    func retry(_ request: Request,
               for session: Session,
               dueTo error: Error,
               completion: @escaping (RetryResult) -> Void) {
        lock.lock()
        defer { lock.unlock() }
    
        // 重试次数检查
        guard currentRetryCount < DomainManager.shared.maxTryCount else {
            return completion(.doNotRetryWithError(error))
        }
        
        // 错误分析
        guard shouldRetry(for: error) else {
            return completion(.doNotRetry)
        }
        
        // 记录日志
        logSwitchEvent(error: error)
        
        DomainManager.shared.reportFailure(for: DomainManager.shared.currentDomain)
        
        currentRetryCount += 1
        
        completion(.retryWithDelay(retryDelay))
    }
    
    private func shouldRetry(for error: Error) -> Bool {
        // 状态码检查
        if let afError = error.asAFError,
           let code = afError.responseCode,
           filteredStatusCodes.contains(code) {
            return false
        }
        
        // 特定错误类型检查
        if let afError = error.asAFError,
           case .sessionTaskFailed(let error) = afError,
           (error as NSError).code == NSURLErrorCancelled {
            return false
        }
        
        return currentRetryCount <= DomainManager.shared.maxTryCount
    }
    
    private func logSwitchEvent(error: Error) {
        let errorInfo: String
        if let afError = error.asAFError {
            errorInfo = "\(afError.underlyingError?.localizedDescription ?? afError.errorDescription ?? "未知错误")"
        } else {
            errorInfo = error.localizedDescription
        }
        
        xlog("[DomainSwitch] 切换到 \(DomainManager.shared.currentDomain)，原因: \(errorInfo)")
    }
    
}

//
//import Alamofire
//
///// 复合型拦截器（域名管理+认证刷新）
//final class DomainAuthInterceptor: RequestInterceptor {
//    // 配置参数
//    private let maxRetryCount: Int = 3
//    private var currentRetryCount = 0
//    private let retryDelay: TimeInterval = 1.0
//    
//    // 线程安全计数器
//    private let lock = NSLock()
//    
//    func adapt(_ urlRequest: URLRequest,
//               for session: Session,
//               completion: @escaping (Result<URLRequest, Error>) -> Void) {
//        var request = urlRequest
//        
//        // 1. 域名切换逻辑
//        if let originalUrl = request.url,
//           let newUrl = DomainManager.shared.switchDomain(for: originalUrl) {
//            request.url = newUrl
//        }
//        
//        // 2. 添加认证头
//        if let credential = AuthManager.shared.validCredential {
//            request.headers.add(.authorization(bearerToken: credential.accessToken))
//            request.headers.add(name: "X-Request-ID", value: UUID().uuidString)
//        }
//        
//        completion(.success(request))
//    }
//    
//    func retry(_ request: Request,
//               for session: Session,
//               dueTo error: Error,
//               completion: @escaping (RetryResult) -> Void) {
//        lock.lock()
//        defer { lock.unlock() }
//        
//        // 3. 重试条件判断
//        guard shouldRetry(request: request, error: error) else {
//            return completion(.doNotRetry)
//        }
//        
//        // 4. 认证刷新流程
//        if isAuthError(error) {
//            refreshToken { [weak self] success in
//                guard let self else { return }
//                self.handleRetryResult(success: success,
//                                     completion: completion)
//            }
//        } else {
//            handleRetryResult(success: true, completion: completion)
//        }
//    }
//    
//    // MARK: - Private Methods
//    private func shouldRetry(request: Request, error: Error) -> Bool {
//        guard currentRetryCount < maxRetryCount else { return false }
//        
//        // 5. 排除特定状态码
//        guard let statusCode = request.response?.statusCode else { return true }
//        return !Set([400, 401, 403, 404]).contains(statusCode)
//    }
//    
//    private func isAuthError(_ error: Error) -> Bool {
//        guard let afError = error.asAFError,
//              case let .responseValidationFailed(reason) = afError,
//              case let .unacceptableStatusCode(code) = reason else {
//            return false
//        }
//        return code == 401
//    }
//    
//    private func refreshToken(completion: @escaping (Bool) -> Void) {
//        AuthManager.shared.refreshToken { result in
//            switch result {
//            case .success: completion(true)
//            case .failure: completion(false)
//            }
//        }
//    }
//    
//    private func handleRetryResult(success: Bool,
//                                 completion: @escaping (RetryResult) -> Void) {
//        currentRetryCount += 1
//        success ? completion(.retryWithDelay(retryDelay))
//               : completion(.doNotRetryWithError(AuthError.tokenRefreshFailed))
//    }
//}



